import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { getDashboardStats, getDashboardTrends } from '@/api/dashboard'

const initialState = {
  stats: null,
  trends: null,
  loading: false,
  error: null,
}

// 获取Dashboard统计数据
export const fetchDashboardStats = createAsyncThunk(
  'dashboard/fetchDashboardStats',
  async (_, { rejectWithValue }) => {
    try {
      const data = await getDashboardStats()
      return data
    } catch (error) {
      return rejectWithValue(error.message)
    }
  }
)

// 获取趋势数据
export const fetchDashboardTrends = createAsyncThunk(
  'dashboard/fetchDashboardTrends',
  async (_, { rejectWithValue }) => {
    try {
      const data = await getDashboardTrends()
      return data
    } catch (error) {
      return rejectWithValue(error.message)
    }
  }
)

const dashboardSlice = createSlice({
  name: 'dashboard',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null
    },
  },
  extraReducers: (builder) => {
    builder
      // 获取统计数据
      .addCase(fetchDashboardStats.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchDashboardStats.fulfilled, (state, action) => {
        state.loading = false
        state.stats = action.payload.data || action.payload
      })
      .addCase(fetchDashboardStats.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload
      })
      // 获取趋势数据
      .addCase(fetchDashboardTrends.pending, (state) => {
        state.loading = true
      })
      .addCase(fetchDashboardTrends.fulfilled, (state, action) => {
        state.loading = false
        state.trends = action.payload.data || action.payload
      })
      .addCase(fetchDashboardTrends.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload
      })
  },
})

export const { clearError } = dashboardSlice.actions
export default dashboardSlice.reducer

